home *** CD-ROM | disk | FTP | other *** search
- Path: mainframe.webgenesis.com!user
- From: vance@webgenesis.com (Vance Huntley)
- Newsgroups: comp.lang.c++
- Subject: Re: How best to handle constructor failure?
- Date: Fri, 05 Jan 1996 08:52:05 -0500
- Organization: WebGenesis, Inc.
- Sender: vrh1@cornell.edu (Verified)
- Message-ID: <vance-0501960852050001@mainframe.webgenesis.com>
- References: <4c36gl$5e5@nnrp1.news.primenet.com> <4cimnp$hne@news1.panix.com>
- NNTP-Posting-Host: mainframe.webgenesis.com
- X-Newsreader: Value-Added NewsWatcher 2.1d3+
-
- > I noticed that there was another thread on constructors that was
- recently posted,
- > where a suggestion was made to use a seperate initialization function
- (what I called
- > a "test" method"). I have done this upon occasion, but I need to
- overload operators,
- > and hence there will be compiler-generated, implicit constructor calls
- which would
- > not include execution of the seperate initializer method! The issue of
- dealing with
- > constructors that can fail appears to be a complex one. Perhaps a good thread
- > will start on the subject!.
- >
-
-
- One (not very elegant) solution I have used in the past (when my compiler
- didn't support exceptions goes like this:
-
- class ValidatedObject
- {
- public:
- CanFailObject() { mIsValid = false; }
-
- Boolean IsValid() { return mIsValid; }
-
- void Invalidate() { mIsValid = false; }
-
- void Validate() { mIsValid = true; }
-
- private:
- Boolean mIsValid;
- };
-
-
-
- class AnObject : public ValidatedObject
- {
- AnObject();
-
- void CriticalOperation();
- };
-
-
-
- AnObject::AnObject()
- {
- // do lots of allocation and other things that may well fail
-
- if( all of the stuff above was sucessfull )
- Validate();
- }
-
-
-
- AnObject::CriticalOperation()
- {
- if( IsValid() )
- {
- // do stuff that would have crashed my machine if the
- // object was poorly constructed
- }
- else
- {
- // do some error handling
- }
-
- }
-
-
- This works, in general, even for objects derived from AnObject.
-
- Now that I work in a compiler environment which supports exceptions, I use
- them happily and often.
-
- Vance
-